<template>
	<view class="container" style="padding-bottom: 100px" v-if="isLoaded">
		<view class="content">
			<view class="form-content">
				<form class="l-form">
					<view class="l-form-item">
						<view class="l-lbl required">桌位名称:</view>
						<view class="l-form-right l-form-input">
							<input class="l-input" v-model="form.name" @blur="onBlurEvent($event)" id="name" />
						</view>
					</view>
					<view class="l-form-item">
						<view class="l-lbl required">所属区域:</view>
						<picker class="form-item-right picker" @change="pickerFoodDeskCategoryChange" v-model="form.typeId" :range="FoodDeskCategoryList" :range-key="'name'">
							<view>
								{{ FoodDeskCategoryList.some((item) => item.id == form.typeId) ? FoodDeskCategoryList.find((item) => item.id == form.typeId).name : '无' }}
							</view>
						</picker>
					</view>
					<view class="l-form-item">
						<view class="l-lbl required" style="font-size: 12px">标准用餐人数:</view>
						<view class="l-form-right l-form-input">
							<input type="number" class="l-input" v-model="form.manQty" @blur="onBlurEvent($event)" id="manQty" />
						</view>
					</view>
					<view class="l-form-item">
						<view class="l-lbl required">餐台号:</view>
						<view class="l-form-right l-form-input">
							<input class="l-input" v-model="form.number" id="number" @blur="onBlurEvent($event)" />
						</view>
					</view>
					<view class="l-form-item">
						<view class="l-lbl">排序:</view>
						<view class="l-form-right l-form-input">
							<input type="number" class="l-input" v-model="form.sort" @blur="onBlurEvent($event)" />
						</view>
					</view>
					<view class="l-form-item">
						<view class="l-lbl">使用状态:</view>
						<!-- <radio-group class="l-form-right" @change="radioStatusChange">
              <label style="margin-right: 30rpx">
                <radio :value="1" :checked="form.status == 1" />
                <text>正常</text>
              </label>
              <label>
                <radio :value="0" :checked="form.status == 0" />
                <text>禁用</text>
              </label>
            </radio-group> -->
						<u-radio-group v-model="form.status">
							<u-radio activeColor="#edac2f" :customStyle="{ marginTop: '12rpx' }" label="正常" :name="1"></u-radio>
							<u-radio activeColor="#edac2f" :customStyle="{ marginLeft: '8px', marginTop: '12rpx' }" label="禁用" :name="0"></u-radio>
						</u-radio-group>
					</view>
					<view class="l-form-item">
						<view class="l-lbl">是否快餐台:</view>
						<!-- <radio-group class="l-form-right" @change="radioFastFoodChange">
              <label style="margin-right: 30rpx">
                <radio :value="1" :checked="form.fastFood == 1" />
                <text>是</text>
              </label>
              <label>
                <radio :value="0" :checked="form.fastFood == 0" />
                <text>否</text>
              </label>
            </radio-group> -->
						<u-radio-group v-model="form.fastFood">
							<u-radio activeColor="#edac2f" :customStyle="{ marginTop: '12rpx' }" label="是" :name="1"></u-radio>
							<u-radio activeColor="#edac2f" :customStyle="{ marginLeft: '8px', marginTop: '12rpx' }" label="否" :name="0"></u-radio>
						</u-radio-group>
					</view>
				</form>
			</view>
			<view style="justify-content: space-between; display: flex; margin-top: 10px; background-color: #fff; padding: 30rpx">
				<view class="lbl lbl-title" style="font-weight: bold">默认菜式</view>
				<view class="form-item-right" style="display: flex; flex: unset; justify-content: flex-end; color: #f3c45d; font-weight: bold" @click="addFoodClick">新增</view>
			</view>
			<view class="spec-container">
				<view class="spec-body">
					<block v-if="form.deskFoodList.length > 0">
						<view>
							<view class="items" style="border-bottom: 1px solid #cacaca; padding: 8px 0">
								<view class="is-default">菜品名称</view>
								<view class="spec-name task-price">规格名称</view>
								<view class="price task-option">数量</view>
								<view class="price task-option">按开台人数</view>
								<view class="btns task-btn">操作</view>
							</view>
						</view>
						<view v-for="(item, index) in form.deskFoodList" :key="item.id" class="items">
							<view class="is-default">
								<text>
									{{ item.name }}
								</text>
							</view>
							<view class="spec-name task-price">{{ item.foodSpecName }}</view>
							<view class="price task-option">
								<input
									style="width: 40px; border-bottom: 1px solid #cacaca; padding: 0 2px"
									type="number"
									v-model="form.deskFoodList[index].quantity"
									id="quantity"
									@blur="onDeskFoodBlurEvent($event)"
								/>
							</view>
							<view class="price task-option">
								<checkbox-group @change="withPersonChange($event, index)">
									<checkbox :value="1" iconColor="#f3c45d" :checked="form.deskFoodList[index].withPerson == 1" />
								</checkbox-group>
							</view>
							<view class="btns task-btn">
								<text class="btn btn-del" @click="btnDelFoodItemClick(index)" style="margin-left: 8px">删除</text>
							</view>
						</view>
					</block>
					<view v-else class="none">
						<image class="image" style="width: 360rpx" src="../../../static/images/none.png" mode=""></image>
						<view>暂无默认菜式，请点击右上角添加~~</view>
					</view>
				</view>
			</view>
		</view>

		<!-- 添加菜品 弹窗 -->
		<u-popup :show="showAddFood" @close="closePopupAddFood" @open="openPopupAddFood" :closeable="true">
			<view class="layout" style="height: 90vh; width: 100vw; background-color: #f7f8fa; font-size: 12px; display: flex">
				<view class="layout-left" style="height: 100%; width: 40vw; overflow-y: scroll">
					<view style="margin: 15rpx; background-color: #fff; border-radius: 10px; padding: 8px 4px" v-for="(item, index) in foodCategoryList" :key="item.id">
						<view class="fold" style="padding: 15rpx 15rpx 15rpx 0">
							<view class="tree-icon" style="margin: 0 5px" v-show="item.fold && item.children.length > 0" @click="unfold(index)">
								<!-- 向右箭头 -->
								<image style="width: 8px; height: 8px" src="/static/images/icon/down.png"></image>
							</view>
							<view @click="unfold(index)" style="margin: 0 5px" class="tree-icon" v-show="!item.fold && item.children.length > 0">
								<!-- 向下箭头 -->
								<image style="width: 8px; height: 8px" src="/static/images/icon/right.png"></image>
							</view>
							<view
								:style="{
									color: foodCategoryId == item.id ? '#f3c45d' : '#000',
									paddingLeft: item.children.length == 0 ? '20px' : '0px'
								}"
								@click="onItemClick(item)"
							>
								{{ item.name }}
							</view>
						</view>
						<block v-if="item.fold">
							<view v-for="(item1, index1) in item.children" class="subtree" :key="item1.id" style="display: flex; padding: 15rpx 15rpx 15rpx 0">
								<view
									class="tree-content"
									style="padding-left: 30px; padding-right: 20rpx"
									:style="{
										color: foodCategoryId == item1.id ? '#f3c45d' : '#000'
									}"
									@click="onItemClick(item1)"
								>
									<text>{{ item1.name }}</text>
								</view>
							</view>
						</block>
					</view>
				</view>
				<view class="layout-right" style="height: 100%; width: 60vw; overflow-y: scroll; padding-top: 40px">
					<block v-if="foodList != null && foodList.length > 0">
						<view class="food-items" style="font-size: 12px" v-for="(food, index) in foodList" :key="index">
							<image class="image" :src="food.image" style="align-self: center" />
							<view class="right" style="padding-bottom: 0">
								<text>名称：{{ food.name }}</text>
								<view class="mt-10">
									<text style="border: 1px solid #f7f8fa">规格：{{ food.foodSpecName }}</text>
								</view>
								<view class="mt-10">
									<text>价格：</text>
									<text class="text-red">￥{{ food.posPrice }}</text>
								</view>
							</view>
							<view class="btn" style="display: flex; align-items: center">
								<text
									style="border: 1px solid #cacaca; padding: 3px 5px; border-radius: 8px; color: #fff"
									:style="{
										'background-color': form.deskFoodList.some((itm) => itm.foodSpecId == food.foodSpecId) ? '#f56c6c' : '#f3c45d'
									}"
									@click="chooseFood(food)"
								>
									{{ form.deskFoodList.some((itm) => itm.foodSpecId == food.foodSpecId) ? '取消' : '选择' }}
								</text>
							</view>
						</view>
					</block>
					<block v-else>
						<view style="display: flex; height: 100%; justify-content: center">
							<u-empty />
						</view>
					</block>
				</view>
			</view>
		</u-popup>
		<li-bottom-btns :zIndex="10" :mode="mode" v-on:btnDelClick="btnDelClick" v-on:btnEditOrSaveSubmitClick="btnEditOrSaveSubmitClick" />
	</view>
</template>
<script>
import { GetFoodDeskCategoryList, GetFoodDeskById, DelFoodDesk, AddFoodDesk, EditFoodDesk, GetFoodCategoryList, GetFood } from '../../../common/api.js';
import { uShowLoading, uHideLoading, uNavigateTo, umodal, utoast, uSetNavigationBarTitle } from '../../../utils/uniUtils.js';
import checker from '../../../common/graceChecker';
import { transfer, transferTypeEnum } from '../../../common/dataTransfer.js';
import { checkerType, modeEnum } from '../../../constants/normalConstants.js';
import { toastIconEnum } from '../../../constants/uiConstants.js';
import { corpId, storeId } from '../../../constants/apiConstants';
export default {
	async onLoad(options) {
		this.mode = options.mode == 'edit' ? 'edit' : 'add';
		uSetNavigationBarTitle((options.mode == 'edit' ? '编辑' : '新增') + this.subject);

		if (this.mode == modeEnum.edit) {
			this.id = options.id;
		}
	},

	async mounted() {
		try {
			uShowLoading();
			// 编辑模式
			if (this.mode == modeEnum.edit) {
				await this.getData();
			} else {
				// 新增模式
				this.form = {
					corpId,
					storeId,
					typeId: 0,
					number: '',
					name: '',
					manQty: 1,
					modifyTime: 0,
					remark: '',
					modifyBy: 0,
					status: 1,
					sort: 0,
					fastFood: 0,
					deskFoodList: []
				};
			}
			this.getOtherData();
		} catch (error) {
			console.log('error', error);
		} finally {
			this.isLoaded = true;
			uHideLoading();
		}
	},
	data() {
		return {
			modeEnum,
			subject: '桌台', // 主题
			rootRoute: 'workbench',
			routeName: 'tableRms',
			mode: 'add', // 模式
			isLoaded: false,
			id: null,
			/* 表单 */
			form: null,
			/* 弹窗 */

			// 数据转换器
			transferRules: [
				{
					name: 'sort',
					type: transferTypeEnum.int
				},
				{
					name: 'name',
					type: transferTypeEnum.trim
				},
				{
					name: 'manQty',
					type: transferTypeEnum.intOrNull
				}
			],
			//表单校验规则
			rules: [
				{
					name: 'name',
					checkType: checkerType.endNotNull,
					errorMsg: '桌台名称不能为空~~'
				},
				{
					name: 'number',
					checkType: checkerType.endNotNull,
					errorMsg: '桌台号不能为空~~'
				}
			],
			lock: false, // 节流锁

			/* 额外数据 */
			FoodDeskCategoryList: [],
			foodCategoryList: [], // 菜品分类列表
			foodCategoryId: 0,
			foodList: [],
			showAddFood: false,

			/* 额外校验规则 */
			/* 额外转换器 */
			deskFoodTransferRules: [
				{
					name: 'quantity',
					type: transferTypeEnum.int
				}
			]
		};
	},

	methods: {
		onBlurEvent(e) {
			// console.log("e-->", e.mp.target.id);
			const name = e.currentTarget.id; // 获取输入框的id
			// 数据转换
			transfer(this.form, this.transferRules);
			// console.log(name, this.form[name]);

			// 表单校验
			if (name != null) {
				let rules = [];
				const rule = this.rules.find((item) => item.name == name);
				// console.log("name", name);
				// console.log("rules", this.rules);
				// console.log("rule", rule);
				// console.log("rule!=null", rule != null);

				if (rule != null) {
					rules.push(rule);
					const isOk = checker.check(this.form, rules);
					// console.log("isOk", isOk);

					if (!isOk) {
						utoast(checker.error, toastIconEnum.none);
					}
				}
			}
		},

		async getData() {
			const res = await GetFoodDeskById(this.id);
			this.form = res.data;
		},

		async getOtherData() {
			GetFoodDeskCategoryList().then((res) => {
				this.FoodDeskCategoryList = res.data.list;
				// 如果是新增模式。。。
				if (this.mode == modeEnum.add) {
					this.form.typeId = this.FoodDeskCategoryList[0].id;
				}
			});

			this.foodCategoryList = (await GetFoodCategoryList()).data.list;
			this.foodCategoryList.forEach((element) => {
				element.label = element.name;
				element.fold = true;
				element.active = false;
				if (element.children.length > 0) {
					element.children.map((item) => {
						item.label = item.name;
						item.fold = true;
					});
				}
			});

			if (this.foodCategoryList.length > 0) {
				this.foodCategoryList[0].active = true;
			}

			// ..
		},

		async insertData() {
			return AddFoodDesk(this.form);
		},

		async delData() {
			return await DelFoodDesk(this.id);
		},

		async editData() {
			return await EditFoodDesk(this.form);
		},

		async btnDelClick() {
			const res = await umodal();
			// 确定删除
			if (res) {
				const result = await this.delData();
				console.log(result);
				if (result.code != null && result.code == 0) {
					await utoast('删除成功！', toastIconEnum.success);
					this.disabled = true;
					setTimeout(() => {
						uNavigateTo(`/pages/${this.rootRoute}/${this.routeName}/list`);
					}, 1000);
				} else {
					await utoast('删除失败！', toastIconEnum.error);
				}
			}
		},

		async btnEditOrSaveSubmitClick() {
			//  节流锁
			if (this.lock) {
				return;
			}

			if (!(await umodal('确认要提交吗？'))) {
				return;
			}

			// 数据转换
			this.form = transfer(this.form, this.transferRules);
			this.form.foods = JSON.stringify(this.form.deskFoodList);

			// 表单校验
			let isOk = checker.check(this.form, this.rules);
			if (!isOk) {
				await utoast(checker.error, toastIconEnum.none);
				return;
			}

			//  提交表单
			const res = this.mode == modeEnum.edit ? await this.editData(this.form) : await this.insertData(this.form);
			if (res?.code == 0) {
				await utoast('操作成功');
				setTimeout(() => {
					uNavigateTo(`/pages/${this.rootRoute}/${this.routeName}/list`);
				}, 1000);
			} else {
				setTimeout(() => {
					this.lock = false;
				}, 2000);
			}
		},

		/* 表单事件 */
		pickerFoodDeskCategoryChange(e) {
			this.form.typeId = this.FoodDeskCategoryList[e.detail.value].id;
		},
		radioStatusChange(e) {
			this.form.status = e.detail.value;
		},
		radioFastFoodChange(e) {
			this.form.fastFood = e.detail.value;
		},
		withPersonChange($event, idx) {
			this.form.deskFoodList[idx].withPerson = $event.detail.value.length > 0 ? 1 : 0;
		},

		/* 额外方法放下面，上面是主干方法 */
		btnDelFoodItemClick(idx) {
			this.form.deskFoodList = this.form.deskFoodList.filter((_item, index) => index != idx);
		},

		onDeskFoodBlurEvent(e) {
			// console.log("e", e);
			const name = e.currentTarget.id; // 获取输入框的id
			// console.log("name", name);
			this.deskFoodTransferRules;
			for (let index = 0; index < this.form.deskFoodList.length; index++) {
				const element = this.form.deskFoodList[index];
				transfer(element, this.deskFoodTransferRules);
			}
		},

		async addFoodClick() {
			this.foodCategoryId = this.foodCategoryList[0].id;
			const res = await GetFood({
				pageNum: 1,
				pageSize: 9999,
				foodCategoryId: this.foodCategoryList[0].id
			});
			this.foodList = res.data.list.filter((item) => item.type == 1);
			this.showAddFood = true;
		},

		closePopupAddFood() {
			this.showAddFood = false;
		},

		openPopupAddFood() {
			this.showAddFood = true;
		},

		async onItemClick(item) {
			console.log(item, 'item');
			if (this.foodCategoryId == item.id) return;
			const res = await GetFood({
				pageNum: 1,
				pageSize: 9999,
				foodCategoryId: item.id
			});
			this.foodCategoryId = item.id;
			this.foodList = res.data.list.filter((item) => item.type == 1);
			//  send Request  GoodsList
		},

		async chooseFood(food) {
			const res = this.form.deskFoodList.some((itm) => itm.foodSpecId == food.foodSpecId);
			if (res) {
				const idx = this.form.deskFoodList.findIndex((itm) => itm.foodSpecId == food.foodSpecId);
				this.form.deskFoodList.splice(idx, 1);
			} else {
				this.form.deskFoodList.push({
					foodId: food.id,
					name: food.name,
					foodSpecName: food.foodSpecName,
					foodSpecId: food.foodSpecId,
					withPerson: 0,
					quantity: 1
				});
			}
		}

		//方法放上面
	}
};
</script>
<style lang="scss" scoped>
@import '~@/static/styles/commonStyle.scss';
.container {
	.spec-container {
		background-color: #fff;
		border-radius: 10px;
		margin: 10px 0;
		padding: 8px 4px;

		.spec-header {
			padding: 10px;
			border-bottom: 1px solid #ededed;
			display: flex;
			justify-content: space-between;
		}

		.spec-body {
			padding: 15px 10px;

			.items {
				display: flex;
				align-items: center;
				justify-content: space-between;
				font-size: 12px;
				border-bottom: 1px solid #cacaca;
				padding: 8px 0;
				&:last-child {
					border-bottom: none;
				}

				.is-default {
					width: 80px;
					display: flex;
					justify-content: center;
					color: #000;
					background-color: #fff;
					.is-default-active {
						color: #fff;
						background-color: #fdc31d;
					}
				}

				.spec-name {
					flex: 1;
					display: flex;
					justify-content: center;
					&.task-price {
						width: 80px;
					}
				}

				.price {
					width: 80px;
					display: flex;
					justify-content: center;
					&.task-option {
						width: 60px;
					}
				}

				.btns {
					width: 90px;
					display: flex;
					justify-content: center;
					&.task-btn {
						width: 70px;
						font-size: 12px;
					}
				}

				.btn {
					border: 1px solid #ededed;
					padding: 12rpx 12rpx;
					border-radius: 5rpx;
					&.btn-del {
						background-color: #f56c6c;
						color: #fff;
					}
				}
			}
		}
	}

	.food-items {
		display: flex;
		padding: 5px;
		border: 1px solid #cacaca;
		border-radius: 8px;
		margin-bottom: 10px;
		margin-right: 10px;
		margin-left: 10px;
		.image {
			width: 160rpx;
			height: 100rpx;
			margin-right: 20rpx;
			border-radius: 8rpx;
			background-color: $bg-color-grey;
		}

		.right {
			flex: 1;
			// height: 160rpx;
			// overflow: hidden;
			display: flex;
			flex-direction: column;
			align-items: flex-start;
			justify-content: space-between;
			border-bottom: 1px #f8f8f8 solid;
			padding-bottom: 20rpx;

			.label {
				display: flex;
				margin-top: 10rpx;

				text {
					display: inline-block;
					padding: 0 8rpx;
					font-size: 20rpx;
					border: 1px #f3c45d solid;
					border-radius: 8rpx;
					margin-right: 10rpx;
				}
			}

			.btn {
				display: flex;
				margin-top: 10rpx;

				text {
					display: inline-block;
					padding: 4rpx 16rpx;
					font-size: 24rpx;
					border: 1px #333 solid;
					border-radius: 8rpx;
					margin-right: 10rpx;
				}
			}
		}
	}
	.img {
		width: 20px;
		height: 20px;
	}

	.fold {
		display: flex;
	}
}
.form-content {
	background-color: #fff;
	padding: 40rpx;
	border-radius: 15rpx;
}
.none {
	font-size: 24rpx;
	text-align: center;
	color: #e3e3e3;
	.image {
		width: 300rpx;
		height: 300rpx;
		margin: 20rpx auto;
	}
}
</style>
